import React, { Component } from "react";
import {
  Table,
  Input,
  Button,
  Space,
  Divider,
  Popconfirm,
  message,
  Badge,
} from "antd";
import Highlighter from "react-highlight-words";
import {
  SearchOutlined,
  DeleteOutlined,
  BarsOutlined,
} from "@ant-design/icons";
import {
  Deliverylist,
  Deliverydelete,
  Deliveryedit,
} from "../../../services/auth";
import "./index.css";

export default class DeliveryList extends Component {
  constructor(props) {
    super(props);
    this.state = {
      searchText: "",
      searchedColumn: "",
      dataSource: [],
    };
  }
  // 用于判断状态的函数，帮助生成badge
  judgeStatus = (status) => {
    switch (status) {
      case "已完成":
        return "success";
      case "待发货":
        return "error";
      case "在途中":
        return "processing";
      default:
        return "default";
    }
  };

  componentDidMount() {
    Deliverylist().then(
      (response) => {
        //拿到我们想要渲染的数据(res)
        this.setState({
          dataSource: response.data,
        });
      },
      (error) => {
        console.log("失败了", error);
      }
    );
  }
  // 搜索框函数
  getColumnSearchProps = (dataIndex) => ({
    filterDropdown: ({
      setSelectedKeys,
      selectedKeys,
      confirm,
      clearFilters,
    }) => (
      <div style={{ padding: 8 }}>
        <Input
          ref={(node) => {
            this.searchInput = node;
          }}
          placeholder={`Search ${dataIndex}`}
          value={selectedKeys[0]}
          onChange={(e) =>
            setSelectedKeys(e.target.value ? [e.target.value] : [])
          }
          onPressEnter={() =>
            this.handleSearch(selectedKeys, confirm, dataIndex)
          }
          style={{ marginBottom: 8, display: "block" }}
        />
        <Space>
          <Button
            type="primary"
            onClick={() => this.handleSearch(selectedKeys, confirm, dataIndex)}
            icon={<SearchOutlined />}
            size="small"
            style={{ width: 90 }}
          >
            搜索
          </Button>
          <Button
            onClick={() => this.handleReset(clearFilters)}
            size="small"
            style={{ width: 90 }}
          >
            重置
          </Button>
          <Button
            type="link"
            size="small"
            onClick={() => {
              confirm({ closeDropdown: false });
              this.setState({
                searchText: selectedKeys[0],
                searchedColumn: dataIndex,
              });
            }}
          >
            Filter
          </Button>
        </Space>
      </div>
    ),
    filterIcon: (filtered) => (
      <SearchOutlined style={{ color: filtered ? "#1890ff" : undefined }} />
    ),
    onFilter: (value, record) =>
      record[dataIndex]
        ? record[dataIndex]
            .toString()
            .toLowerCase()
            .includes(value.toLowerCase())
        : "",
    onFilterDropdownVisibleChange: (visible) => {
      if (visible) {
        setTimeout(() => this.searchInput.select(), 100);
      }
    },
    render: (text) =>
      this.state.searchedColumn === dataIndex ? (
        <Highlighter
          highlightStyle={{ backgroundColor: "#ffc069", padding: 0 }}
          searchWords={[this.state.searchText]}
          autoEscape
          textToHighlight={text ? text.toString() : ""}
        />
      ) : (
        text
      ),
  });

  handleSearch = (selectedKeys, confirm, dataIndex) => {
    confirm();
    this.setState({
      searchText: selectedKeys[0],
      searchedColumn: dataIndex,
    });
  };

  handleReset = (clearFilters) => {
    clearFilters();
    this.setState({ searchText: "" });
  };

  // 传给抽屉用于编辑的函数
  handleEditClick = (value) => {
    // 先传值
    Deliveryedit(value).then(
      (response) => {
        if (response.data === "success") {
          message.success("修改成功");
          Deliverylist().then(
            (response) => {
              this.setState({
                dataSource: response.data,
              });
            },
            (error) => {
              console.log("失败了", error);
            }
          );
        } else {
          message.info("修改失败，请重试");
        }
      },
      (error) => {
        console.log("数据获取失败", error);
      }
    );
  };
  // 用于删除的函数
  handleDelete = (id) => {
    Deliverydelete(id).then(
      (response) => {
        if (response.data === "success") {
          message.success("删除成功");
          // 删除成功后改变页面内容
          const dataSource = [...this.state.dataSource];
          this.setState({
            dataSource: dataSource.filter((item) => item.id !== id),
          });
        } else message.info("删除失败，请重试");
      },
      (error) => {
        console.log("数据获取失败", error);
      }
    );
  };

  render() {
    const { DisplayDetail } = this.props;
    const columns = [
      {
        title: "发货单编号",
        dataIndex: "id",
        align: "center",
        ...this.getColumnSearchProps("id"),
        sorter: (a, b) => a.id - b.id,
      },
      {
        title: "公司",
        dataIndex: "company_name",
        align: "center",
        className: "delivery-name",
        ...this.getColumnSearchProps("company_name"),
      },
      {
        title: "总价",
        dataIndex: "total_price",
        align: "center",
        className: "delivery-price",
        ...this.getColumnSearchProps("total_price"),
      },
      {
        title: "创建时间",
        dataIndex: "docum_date",
        align: "center",
        ...this.getColumnSearchProps("docum_date"),
      },
      {
        title: "预计送达时间",
        dataIndex: "req_deliv_date",
        key: "valid_from",
        align: "center",
        className: "delivery-date",
        ...this.getColumnSearchProps("req_deliv_date"),
      },
      {
        title: "状态",
        dataIndex: "status",
        align: "center",
        filters: [
          { text: "待发货", value: "待发货" },
          { text: "已拣配", value: "已拣配" },
          { text: "在途中", value: "在途中" },
          { text: "已完成", value: "已完成" },
        ],
        render: (status) => {
          return <Badge status={this.judgeStatus(status)} text={status} />;
        },
        onFilter: (value, record) => record.status.indexOf(value) === 0,
      },
      {
        title: "",
        key: "action",
        align: "center",
        render: (record) => (
          <Space>
            <Button
              type="text"
              size="small"
              icon={<BarsOutlined />}
              style={{ fontWeight: "bold" }}
              onClick={() => {
                DisplayDetail(record);
              }}
            >
              详情
            </Button>
            <Divider type="vertical" />
            <Popconfirm
              title="确定要删除吗？"
              onConfirm={() => this.handleDelete(record.id)}
            >
              <Button
                danger
                type="text"
                size="small"
                icon={<DeleteOutlined />}
                style={{ fontWeight: "bold" }}
                disabled={record.status !== "待发货"}
              >
                删除
              </Button>
            </Popconfirm>
          </Space>
        ),
      },
    ];
    return (
      <div>
        <Table
          className="table"
          columns={columns}
          dataSource={this.state.dataSource}
          rowKey={(record) => record.id}
          pagination={{ pageSize: 7 }}
          size="small"
          style={{ fontWeight: "bold" }}
        />
      </div>
    );
  }
}
